package net_thread_test;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientThread extends Thread{
    @Override
    public void run(){
        try {
            //创建一个客户端对象，第一个参数是 服务器IP地址 ， 第二个参数是 端口号
            Socket socket = new Socket("10.2.208.184",8686);
            //创建一个输出流，向服务器传递信息
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
            bufferedWriter.write("已发送");
            bufferedWriter.newLine();
            bufferedWriter.flush();

            Scanner scanner = new Scanner(System.in);
            System.out.println("客户端发送：");
            String str = scanner.nextLine();
            bufferedWriter.write(str);
            bufferedWriter.newLine();
            // 自定义一个通信协议：消息发送末尾 使用 eof 作为结束标志位
            bufferedWriter.write("eof");
            bufferedWriter.write("\n");
            bufferedWriter.flush();

            //创建一个输入流对象，用来接收服务器返回的信息
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
            while (true){
                String strMsg = bufferedReader.readLine();
                if (strMsg!=null && !strMsg.equals("eof")){
                    System.out.println("客户端接收："+strMsg);
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
